package org.example.service.impl;

import org.example.domain.User;
import org.example.service.MyUserDetailsService;
import org.example.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MyUserDetailsServiceImpl implements MyUserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        if (!StringUtils.hasText(account)){
            throw new RuntimeException("用户名不能为空!!!");
        }
        User user = (User) userService.getUserByName(account).getData();
        if (user == null){
            throw new RuntimeException("此账号还未注册");
        }
        List<GrantedAuthority> grantedAuthorityList =
                AuthorityUtils.commaSeparatedStringToAuthorityList(user.getAdmin() == 0 ? "ROLE_admin" : "ROLE_normal");
        return new org.springframework.security.core.userdetails.User(user.getAccount(),user.getPassword(),grantedAuthorityList);
    }
}
